#!/usr/bin/env python3
"""
最终解密演示 - 展示我们的成果和限制
"""

import base64
from collections import Counter

def demonstrate_decryption():
    """演示解密过程"""
    print("🔐 === 通义千问API加密解密演示 ===\n")
    
    # 1. 加载数据
    with open('encript_body.txt', 'r') as f:
        encrypted = f.read().strip()
    
    print(f"1️⃣ 原始加密数据 (前100字符):")
    print(f"   {encrypted[:100]}...")
    print(f"   长度: {len(encrypted)} 字符")
    print(f"   字符集: {len(set(encrypted))} 个唯一字符")
    
    # 2. 自定义Base64解码
    charset = sorted(set(encrypted))
    charset_str = ''.join(charset)
    print(f"\n2️⃣ 自定义Base64字符集:")
    print(f"   {charset_str}")
    
    # 标准Base64
    std_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    
    # 创建映射
    mapping = {}
    for i, char in enumerate(charset_str):
        if i < len(std_base64):
            mapping[char] = std_base64[i]
    
    # 转换
    translated = ''.join(mapping.get(c, c) for c in encrypted)
    padding = (4 - len(translated) % 4) % 4
    translated += '=' * padding
    
    # 解码
    decoded = base64.b64decode(translated)
    print(f"\n3️⃣ Base64解码后:")
    print(f"   长度: {len(decoded)} 字节")
    print(f"   前50字节(hex): {decoded[:50].hex()}")
    
    # 3. 应用已知的字节映射
    known_mapping = {
        0xa1: ord('m'),
        0xf3: ord('o'),
        0x6b: ord('d'),
        0x31: ord('e'),
        0xb0: ord('l'),
        0x69: ord('"'),
        0x01: ord(':'),
        0x90: ord(' ')
    }
    
    print(f"\n4️⃣ 已确认的字符映射:")
    for enc, dec in sorted(known_mapping.items()):
        print(f"   0x{enc:02x} -> '{chr(dec)}'")
    
    # 部分解密
    partial = bytearray()
    mapped_count = 0
    for byte in decoded:
        if byte in known_mapping:
            partial.append(known_mapping[byte])
            mapped_count += 1
        else:
            partial.append(byte)
    
    print(f"\n5️⃣ 部分解密结果:")
    print(f"   已映射字节: {mapped_count}/{len(decoded)} ({mapped_count/len(decoded)*100:.1f}%)")
    
    # 查找 "model" 出现的位置
    model_positions = []
    pos = 0
    while True:
        pos = partial.find(b"model", pos)
        if pos == -1:
            break
        model_positions.append(pos)
        pos += 1
    
    print(f"   'model' 出现次数: {len(model_positions)}")
    
    # 显示包含 "model" 的片段
    if model_positions:
        print(f"\n   包含 'model' 的片段:")
        for i, pos in enumerate(model_positions[:3]):
            start = max(0, pos - 20)
            end = min(len(partial), pos + 30)
            snippet = partial[start:end]
            
            # 将不可打印字符替换为 .
            display = bytearray()
            for b in snippet:
                if 32 <= b <= 126:
                    display.append(b)
                else:
                    display.append(ord('.'))
            
            print(f"   {i+1}. ...{bytes(display).decode('ascii')}...")
    
    # 6. 统计分析
    print(f"\n6️⃣ 统计分析:")
    
    # 未映射的字节
    unmapped = set()
    for byte in decoded:
        if byte not in known_mapping:
            unmapped.add(byte)
    
    print(f"   未映射的唯一字节: {len(unmapped)} 个")
    
    # 字节频率
    byte_freq = Counter(decoded)
    print(f"   最频繁的未映射字节:")
    count = 0
    for byte_val, freq in byte_freq.most_common():
        if byte_val not in known_mapping:
            print(f"     0x{byte_val:02x}: {freq}次")
            count += 1
            if count >= 5:
                break

def show_next_steps():
    """显示下一步建议"""
    print("\n\n📋 === 下一步建议 ===")
    
    print("\n1. 动态调试方法:")
    print("   ```bash")
    print("   # 找到Lingma进程")
    print("   ps aux | grep Lingma")
    print("   ")
    print("   # 使用GDB附加")
    print("   sudo gdb -p <PID>")
    print("   ")
    print("   # 在字符串操作函数设置断点")
    print("   break strcpy")
    print("   break memcpy")
    print("   ```")
    
    print("\n2. 获取更多样本:")
    print("   - 发送包含 'test', 'hello', '123' 等已知内容的请求")
    print("   - 捕获对应的加密请求")
    print("   - 通过对比找出更多字符映射")
    
    print("\n3. 内存搜索:")
    print("   ```python")
    print("   # 搜索可能的映射表（256字节数组）")
    print("   # 映射表特征：每个字节值出现一次")
    print("   ```")
    
    print("\n4. 使用官方方式:")
    print("   考虑使用通义千问的官方SDK或API文档")
    print("   https://help.aliyun.com/zh/dashscope/")

def main():
    """主函数"""
    demonstrate_decryption()
    show_next_steps()
    
    print("\n\n✅ === 总结 ===")
    print("我们成功：")
    print("  ✓ 识别了加密方案（自定义Base64 + 字节替换）")
    print("  ✓ 解码了第一层加密")
    print("  ✓ 部分破解了字节替换（能看到 'model' 等内容）")
    print("\n未完成：")
    print("  ✗ 完整的245字节映射表")
    print("  ✗ 完全解密JSON内容")
    print("\n这个加密虽然不是很复杂，但没有完整映射表就无法完全破解。")

if __name__ == "__main__":
    main()